import os
import shutil

file_dir = 'I:/txt/xinnuan'
# file_dir = '/home/python/txt/xinnuan2'

# 合并文件
def merge(dir):
    if not os.path.exists(dir):
        print("目录不存在！")
        return
    listdir = os.listdir(dir)
    for name in listdir:
        path = getpath(dir,name)
        if ismerge(path): # 判断是否符合合并条件 要不要都行
            merging(path,name,dir)

# 合并文件
def merging(dir,fileName,savePath):
    if not os.path.exists(dir):
        return
    if not os.path.exists(savePath):
        return
    if not os.path.isdir(dir):
        return
    print("目录文件夹：%s 正在合并……"%dir)
    print("正在生成文件：%s.txt ……"%fileName)
    filePath = getpath(savePath,fileName) + '.txt'
    if os.path.exists(filePath):
        os.remove(filePath)
    with open(filePath,mode='a',encoding='gbk')as f:
        fileList = os.listdir(dir)
        fileList.sort()
        print(fileList)
        for name in fileList:
            if not name.endswith('.hj'):
                continue
            path = getpath(dir, name)
            if not os.path.isfile(path):
                continue
            with open(path,mode='r',encoding='gbk') as r:
                line = r.readline()
                while line:
                    f.write(line)
                    line = r.readline()

    print("文件《%s.txt》生成成功！！！" % fileName)
    # 删除已合并文件夹
    shutil.rmtree(dir)



def getpath(dir,name):
    return dir + '/' + name


# 合并条件判断
def ismerge(dir):
    if not os.path.exists(dir):
        return False
    if not os.path.isdir(dir):
        return False
    listdir = os.listdir(dir)
    for name in listdir:
        path = getpath(dir,name)
        if not os.path.isfile(path):
            return False
        if not path.endswith(".hj"):
            return False
    return True

merge(file_dir)